//
//  WBOAuthViewController.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/15.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
//导入模块
import SVProgressHUD

//OC中没有多继承 用协议来代替
class WBOAuthViewController: UIViewController {

    //定义属性
    let webView = UIWebView()
    override func loadView() {
        //自定义根视图
        self.view = webView
        webView.delegate = self
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "", title: "关闭", target: self, action: #selector(close))
        //在应用发布的时候 千万要注意一定要注销
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName:"", title: "VIP免登录",target: self, action: #selector(fillAccount))
        //设置背景颜色，使用手写代码创建的控制器的背景颜色是透明的
        self.view.backgroundColor = UIColor.white
        //设置授权页
        loadOauthPage()
    }

    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = '18550005398', document.getElementById('passwd').value = '307518'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }

    func loadOauthPage() {
//        https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url =  URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
    }

    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    //在页面关闭的时候 dismiss掉指示器
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

    }



    //MARK:网页的代理方法
extension WBOAuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView){
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView){
        SVProgressHUD.dismiss()
    }

    //将代理方法抽取到分类中实现 将模块的功能独立起来 更加好维护
//一般协议方法返回值为bool类型 如果返回true 就可以正常工作否则就不能够正常工作
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    // ^    Optional(http://www.baidu.com/?code=ddbc6f77b1ba9641eb776f79479ff449

    let urlString = request.url?.absoluteString ?? ""
    //判断urlStirng 中是否包含了特殊的标记吧如果包含就可以截取code
    let flag = "code="
    if urlString.contains(flag) {
        //能够截取code
        let query = request.url?.query ?? ""
        let code = (query as NSString).substring(from: flag.characters.count)
        print(code)
        
        //获取了code之后就应该使用code 获取用户的token(访问接口的唯一标识)
        //如果获取了code之后就应该 return false 不加载页面
        WBUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSuccess: Bool) -> () in
            if !isSuccess {
                //没有成功
                SVProgressHUD.showError(withStatus: "没有网络")
                return
            }
            
            //请求成功
            print("请求成功")
            
            //object: 表示哪个对象发通知,通常用来传参数
           NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: "Welcome")
//            UIApplication.shared.keyWindow?.rootViewController = WBWelcomeController()
        })
        return false
    }
    
    return true
}

    

}
